<template>
  <div>
    <div class="grid-container">
      <div v-for="item in Object.keys(data)" :key="item" class="card">
        <div class="card-title" @click="toggleCard(item)">
          <div>{{ item }}</div>
          <div class="collapse-icon" :class="{ 'expanded': expandedCards[item], 'collapsed': !expandedCards[item] }">
            <el-icon :size="16"><ArrowDown /></el-icon>
          </div>
        </div>
        
        <div class="card-content-wrapper" 
             :style="{ height: expandedCards[item] ? contentHeights[item] + 'px' : '0' }">
          <div class="card-content" :ref="el => setContentRef(el, item)">
            <div v-for="item2 in data[item]" :key="item2.key" class="form-item">
              <!-- 下拉框 -->
              <div v-if="item2.type === 'select'" class="form-item-label">
                <div class="tableHeaderName">{{ item2.name }}</div>
                <el-select size="small" v-model="internalValue[item2.key]" placeholder="请选择" @change="handleChange">
                  <el-option v-for="item3 in item2.value" :key="item3" :label="item3" :value="item3" />
                </el-select>
              </div>
              <!-- 多选框 -->
              <div v-else-if="item2.type === 'checkbox'" class="form-item-label">
                <div class="tableHeaderName">{{ item2.name }}</div>
                <el-checkbox-group size="small" v-model="internalValue[item2.key]" @change="handleChange">
                  <el-checkbox v-for="item3 in item2.value" :key="item3" :value="item3" class="checkboxMagging">
                    <div :style="'background-color:' + item3 + ';'" class="checkboxColor"></div>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <!-- 开关 -->
              <div v-else-if="item2.type === 'switch'" class="form-item-label">
                <div class="tableHeaderName">{{ item2.name }}</div>
                <el-switch size="small" v-model="internalValue[item2.key]" @change="handleChange" />
              </div>
              <!-- 数组输入框 -->
              <div v-else-if="item2.type === 'input_array'" class="form-item-label">
                <div class="tableHeaderName">{{ item2.name }}</div>
                <el-input size="small" v-model="internalValue[item2.key]" :placeholder="item2.value" @input="handleChange" />
              </div>
              <!-- 多选下拉框 -->
              <div v-else-if="item2.type === 'input_select'" class="form-item-label">
                <div class="tableHeaderName">{{ item2.name }}</div>
                <el-select size="small" v-model="internalValue[item2.key]" placeholder="请选择" multiple @change="handleChange">
                  <el-option v-for="item3 in item2.value" :key="item3" :label="item3" :value="item3" />
                </el-select>
              </div>
              <!-- 输入框 -->
              <div v-else-if="item2.type === 'input'" class="form-item-label">
                <div class="tableHeaderName">{{ item2.name }}</div>
                <div v-if="Array.isArray(item2.value)">
                  <el-input-number size="small" v-model="internalValue[item2.key]" :min="item2.value[0]"
                    :max="item2.value[1]" :step="(item2.value[1] - item2.value[0]) / 100" @change="handleChange" />
                </div>
                <div v-else>
                  <el-input size="small" v-model="internalValue[item2.key]" @input="handleChange" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeMount, nextTick } from "vue";
import { ArrowDown } from '@element-plus/icons-vue'

const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  modelValue: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:modelValue']);

// 使用内部值来避免直接修改props
const internalValue = ref({});

// 存储卡片展开状态的ref
const expandedCards = ref({});

// 存储内容高度和DOM引用
const contentHeights = ref({});
const contentRefs = ref({});

// 设置内容引用并计算高度
const setContentRef = (el, key) => {
  if (el) {
    contentRefs.value[key] = el;
    updateContentHeight(key);
  }
};

// 更新内容高度
const updateContentHeight = (key) => {
  nextTick(() => {
    if (contentRefs.value[key]) {
      contentHeights.value[key] = contentRefs.value[key].scrollHeight+10;
    }
  });
};

// 初始化 returnData 的函数
const dataInitToReturn = (dataSource) => {
  const result = {};
  // 遍历 dataSource 的所有一级 key
  Object.keys(dataSource).forEach((key) => {
    // 初始化卡片展开状态为true
    expandedCards.value[key] = true;
    // 只处理有配置项的数组
    if (Array.isArray(dataSource[key]) && dataSource[key].length > 0) {
      dataSource[key].forEach((item) => {
        // 如果type是select，则默认值为第一个值
        if (item.type === "select") {
          result[item.key] = item.value[0];
        } else if (item.type === "checkbox") {
          // 默认全选
          result[item.key] = item.value;
        } else if (item.type === "switch") {
          result[item.key] = false;
        } else if (item.type === "input_array") {
          result[item.key] = '';
        } else if (item.type === "input_select") {
          result[item.key] = item.value;
        } else if (item.type === "input") {
          // 对数字输入框特殊处理
          if (Array.isArray(item.value)) {
            result[item.key] = item.value[1]; // 初始化为最大值
          } else {
            result[item.key] = null; // 普通输入框初始化为 null 而不是空字符串
          }
        }
      });
    }
  });
  return result;
};

// 切换卡片展开状态
const toggleCard = async (cardKey) => {
  expandedCards.value[cardKey] = !expandedCards.value[cardKey];
  await nextTick();
  updateContentHeight(cardKey);
};

// 数据变化时触发
const handleChange = () => {
  emit('update:modelValue', internalValue.value);
};

// 初始化数据
const initData = () => {
  if (Object.keys(props.modelValue).length === 0) {
    // 如果外部没有传入初始值，则自动初始化
    internalValue.value = dataInitToReturn(props.data);
    emit('update:modelValue', internalValue.value);
  } else {
    // 如果外部传入了初始值，使用传入的值
    internalValue.value = { ...props.modelValue };
    // 初始化卡片状态
    Object.keys(props.data).forEach((key) => {
      expandedCards.value[key] = true;
    });
  }
};

// 初始化
onBeforeMount(() => {
  initData();
});

// 监听外部传入的modelValue变化
watch(() => props.modelValue, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(internalValue.value)) {
    internalValue.value = { ...newVal };
  }
}, { deep: true });

// 监听data变化，重新初始化
watch(() => props.data, () => {
  initData();
  // 数据变化后更新高度
  nextTick(() => {
    Object.keys(contentRefs.value).forEach(updateContentHeight);
  });
}, { deep: true });
</script>

<style lang="scss" scoped>
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 15px;
  padding: 15px;

  .card {
    border: 1px solid #e0e0e0;
    border-radius: 2px;
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    transition: box-shadow 0.3s ease;
    height: auto;
    align-self: flex-start;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .card-title {
      font-size: 15px;
      font-weight: 500;
      padding-bottom: 8px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      border-bottom: 1px solid #dbdbdb;
    }

    .card-content-wrapper {
      transition: height 0.3s ease;
      overflow: hidden;
    }

    .card-content {
      display: grid;
      gap: 8px;
      margin-top: 10px;
    }

    .collapse-icon {
      transition: transform 0.3s ease;
      
      &.expanded {
        transform: rotate(0deg);
      }
      
      &.collapsed {
        transform: rotate(-90deg);
      }
    }

    .form-item {
      display: grid;
      gap: 4px;

      &>* {
        width: 100%;
      }

      .form-item-label {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .tableHeaderName {
          margin-right: 5px;
          width: fit-content;
          white-space: nowrap;
          font-size: 13px;
        }

        .el-checkbox-group {
          flex: 1;
          max-width: 150px;
        }

        .el-input {
          max-width: 190px;
          flex: 1;
        }

        .el-select {
          max-width: 190px;
        }
      }
    }
  }

  .checkboxColor {
    width: 20px;
    height: 20px;
    border-radius: 5px;
    box-shadow: 1px 1px 1px 2px rgba(0, 0, 0, 0.1);
  }

  .checkboxMagging {
    margin-right: 10px;
  }
}
</style>